<template>
  <div class="space-y-4 relative z-10">
    <!-- 帖子卡片 -->
    <article
      v-for="post in posts"
      :key="post.id"
      @click="handlePostDetailClick(post.id)"
      class="group bg-white rounded-xl shadow-sm hover:shadow-lg transition-all duration-300 overflow-hidden cursor-pointer border border-gray-100  hover:-translate-y-1"
    >
      <!-- 用户信息头部 -->
      <header class="p-4 pb-3">
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-3">
            <!-- 用户头像 -->
            <button
              @click.stop="handleAvatarClick(post.author.id)"
              class="relative group/avatar flex-shrink-0"
            >
              <div class="w-11 h-11 rounded-full bg-gradient-to-br p-0.5">
                <img
                  :src="post.author.avatar"
                  :alt="post.author.name"
                  class="w-full h-full rounded-full object-cover bg-white"
                />
              </div>
            </button>

            <!-- 用户名和时间 -->
            <div class="flex-1 min-w-0">
              <button
                @click.stop="handleNameClick(post.author.id)"
                class="block font-semibold text-gray-900 hover:text-emerald-600 transition-colors duration-200 truncate text-sm"
              >
                {{ post.author.name }}
              </button>
              <div class="flex items-center text-xs text-gray-500 mt-0.5">
                <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                <span>{{ post.meta.time }}</span>
              </div>
            </div>
          </div>

          <!-- 关注按钮 -->
          <button
            v-if="isShowConcernButton(post.author.id)"
            @click.stop="handleFollowClick(post.author.id)"
            :class="[
              'px-4 py-2 text-sm font-medium rounded-full transition-all duration-200 transform hover:scale-105 shadow-sm hover:shadow-md flex items-center space-x-1',
              isFollowing(post.author.id) 
                ? 'bg-gray-300 text-gray-500 cursor-default hover:scale-100 hover:shadow-sm' 
                : 'bg-gradient-to-r from-emerald-400 to-cyan-400 text-white hover:from-emerald-500 hover:to-cyan-500'
            ]"
          >
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
            </svg>
            <span>{{ isFollowing(post.author.id) ? "已关注" : "关注" }}</span>
          </button>
        </div>
      </header>

      <!-- 帖子内容 -->
      <main class="px-4 pb-3">
        <!-- 标题 -->
        <h2
          class="text-lg font-bold text-gray-900 mb-2 group-hover:text-emerald-600 transition-colors duration-200 line-clamp-2 leading-snug">
          {{ post.content.title }}
        </h2>

        <!-- 正文内容 -->
        <div class="text-gray-700 leading-relaxed mb-3 text-sm">
          <p class="line-clamp-3">{{ post.content.text }}</p>
        </div>

        <!-- 图片网格 - 响应式布局 -->
        <div v-if="post.content.images.length > 0" class="mb-3">
          <!-- 单张图片 -->
          <div v-if="post.content.images.length === 1" class="rounded-lg overflow-hidden">
            <img
              :src="post.content.images[0]"
              :alt="图片"
              class="w-full max-h-80 object-cover hover:scale-105 transition-transform duration-300"
            />
          </div>

          <!-- 两张图片 -->
          <div v-else-if="post.content.images.length === 2" class="grid grid-cols-2 gap-2">
            <div
              v-for="(image, index) in post.content.images"
              :key="index"
              class="aspect-square rounded-lg overflow-hidden bg-gray-100"
            >
              <img
                :src="image"
                :alt="`图片${index + 1}`"
                class="w-full h-full object-cover hover:scale-105 transition-transform duration-300"
              />
            </div>
          </div>

          <!-- 三张图片 -->
          <div v-else-if="post.content.images.length === 3" class="grid grid-cols-3 gap-2">
            <div
              v-for="(image, index) in post.content.images"
              :key="index"
              class="aspect-square rounded-lg overflow-hidden bg-gray-100"
            >
              <img
                :src="image"
                :alt="`图片${index + 1}`"
                class="w-full h-full object-cover hover:scale-105 transition-transform duration-300"
              />
            </div>
          </div>

          <!-- 四张及以上图片 -->
          <div v-else class="grid grid-cols-3 gap-2">
            <!-- 显示前8张图片 -->
            <div
              v-for="(image, index) in post.content.images.slice(0, 8)"
              :key="index"
              class="aspect-square rounded-lg overflow-hidden bg-gray-100"
            >
              <img
                :src="image"
                :alt="`图片${index + 1}`"
                class="w-full h-full object-cover hover:scale-105 transition-transform duration-300"
              />
            </div>

            <!-- 第9个位置：如果图片超过9张，显示剩余数量 -->
            <div
              v-if="post.content.images.length > 8"
              class="aspect-square rounded-lg overflow-hidden bg-gray-100 relative cursor-pointer"
            >
              <img
                :src="post.content.images[8]"
                :alt="更多图片"
                class="w-full h-full object-cover"
              />
              <div v-if="post.content.images.length > 9"
                   class="absolute inset-0 bg-black/50 flex items-center justify-center backdrop-blur-sm">
                <div class="text-center text-white">
                  <div class="text-lg font-bold">+{{ post.content.images.length - 9 }}</div>
                  <div class="text-xs opacity-90">更多</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 图片数量提示 -->
          <div v-if="post.content.images.length > 1" class="mt-2 text-xs text-gray-400 flex items-center">
            <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 2h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V4a2 2 0 012-2z"></path>
            </svg>
            <span>共 {{ post.content.images.length }} 张图片</span>
          </div>
        </div>

        <!-- 标签 -->
        <div v-if="post.content.tags && post.content.tags.length > 0"
             class="flex flex-wrap gap-1.5 mb-3">
          <span
            v-for="(tag, index) in post.content.tags.slice(0, 4)"
            :key="tag"
            :class="[
              'inline-flex items-center px-2 py-1 rounded-full text-xs font-medium transition-colors duration-200 cursor-pointer',
              getTagColor(index)
            ]"
          >
            #{{ tag }}
          </span>
          <span v-if="post.content.tags.length > 4"
                class="inline-flex items-center px-2 py-1 rounded-full text-xs bg-gray-100 text-gray-500">
            +{{ post.content.tags.length - 4 }}
          </span>
        </div>
      </main>

      <!-- 互动区域 -->
      <footer class="px-4 py-3 bg-gradient-to-r from-gray-50 to-gray-50/50 border-t border-gray-100">
        <div class="flex items-center justify-between">
          <!-- 左侧互动按钮 -->
          <div class="flex items-center space-x-6">
            <!-- 点赞 -->
            <button
              @click.stop="toggleLike(post)"
              :class="[
                'flex items-center space-x-1.5 transition-all duration-200 hover:scale-105 text-sm',
                post.stats.liked ? 'text-pink-500' : 'text-gray-500 hover:text-pink-500'
              ]"
            >
              <div :class="[
                'w-7 h-7 rounded-full flex items-center justify-center transition-all duration-200',
                post.stats.liked ? 'bg-pink-100' : 'hover:bg-pink-50'
              ]">
                <svg v-if="post.stats.liked" class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                  <path fill-rule="evenodd"
                        d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z"
                        clip-rule="evenodd"></path>
                </svg>
                <svg v-else class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
                </svg>
              </div>
              <span class="font-medium">{{ formatNumber(post.stats.likes) }}</span>
            </button>

            <!-- 评论 -->
            <button
              class="flex items-center space-x-1.5 text-gray-500 hover:text-cyan-500 transition-all duration-200 hover:scale-105 text-sm">
              <div
                class="w-7 h-7 rounded-full flex items-center justify-center hover:bg-cyan-50 transition-all duration-200">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                </svg>
              </div>
              <span class="font-medium">{{ formatNumber(post.stats.comments) }}</span>
            </button>

            <!-- 分享 -->
            <button
              class="flex items-center space-x-1.5 text-gray-500 hover:text-emerald-500 transition-all duration-200 hover:scale-105 text-sm">
              <div
                class="w-7 h-7 rounded-full flex items-center justify-center hover:bg-emerald-50 transition-all duration-200">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.367 2.684 3 3 0 00-5.367-2.684z"></path>
                </svg>
              </div>
              <span class="font-medium">分享</span>
            </button>
          </div>

          <!-- 右侧浏览量 -->
          <div class="flex items-center space-x-1.5 text-gray-400">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
            </svg>
            <span class="text-sm font-medium">{{ formatNumber(post.stats.views) }}</span>
          </div>
        </div>
      </footer>
    </article>

    <!-- 空状态 -->
    <div v-if="posts.length === 0" class="text-center py-16">
      <div
        class="w-20 h-20 mx-auto mb-4 bg-gradient-to-br from-emerald-100 to-cyan-100 rounded-full flex items-center justify-center">
        <svg class="w-10 h-10 text-emerald-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9a2 2 0 00-2-2h-2m-4-3H9M7 16h6M7 8h6v4H7V8z"></path>
        </svg>
      </div>
      <h3 class="text-lg font-semibold text-gray-900 mb-2">暂无帖子</h3>
      <p class="text-gray-500 text-sm">还没有任何帖子，快来发布第一条动态吧！</p>
      <button
        class="mt-4 px-6 py-2 bg-gradient-to-r from-emerald-400 to-cyan-400 text-white text-sm font-medium rounded-full hover:from-emerald-500 hover:to-cyan-500 transition-all duration-200 transform hover:scale-105 shadow-sm hover:shadow-md">
        发布动态
      </button>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { concernPosts } from "@/mock/post/concernData";
import { communityPosts } from "@/mock/post/communityData.js";
import { squarePosts } from "@/mock/post/squareData.js";
import { userPosts } from "@/mock/post/userData";

export default {
  name: "PostList",
  props: {
    pageType: {
      type: String,
      default: "concern",
      validator: (value) => ["concern", "community", "square", "user"].includes(value)
    },
    communityId: {
      type: Number,
      required: false
    },
    userId: {
      type: [Number, String],
      required: false
    }
  },
  data() {
    return {
      posts: [],
      tagColors: [
        "bg-emerald-100 text-emerald-600 hover:bg-emerald-200",
        "bg-cyan-100 text-cyan-600 hover:bg-cyan-200",
        "bg-pink-100 text-pink-600 hover:bg-pink-200",
        "bg-purple-100 text-purple-600 hover:bg-purple-200",
        "bg-orange-100 text-orange-600 hover:bg-orange-200"
      ],
      followingUsers: new Set() // 用于存储已关注的用户ID
    };
  },
  computed: {
    ...mapState({
      currentUserId: state => state.userId
    })
  },
  created() {
    this.loadPostsByType();
  },
  watch: {
    pageType() {
      this.loadPostsByType();
    }
  },
  methods: {
    loadPostsByType() {
      switch (this.pageType) {
        case "concern":
          this.posts = concernPosts;
          break;
        case "community":
          this.posts = communityPosts;
          break;
        case "square":
          this.posts = squarePosts;
          break;
        case "user":
          this.posts = userPosts;
          break;
        case "postDetail":
          this.posts = [{
            id: 6,
            author: {
              id: 101,
              name: "陈小雨",
              avatar: "https://randomuser.me/api/portraits/women/65.jpg"
            },
            content: {
              title: "我的读书角落改造",
              text: "终于把宿舍的小角落改造成了理想中的读书空间！\n\n改造清单：\n- 暖色调台灯\n- 舒适靠枕\n- 小书架\n- 绿植装饰\n- 复古风格地毯\n\n有了这个舒适的小天地，以后可以安静地看书学习了。最近在读村上春树的《挪威的森林》，真的很喜欢他的文风，大家有什么好书推荐吗？",
              images: [
                "https://images.unsplash.com/photo-1594312915251-48db9280c8f1",
                "https://images.unsplash.com/photo-1507842217343-583bb7270b66",
                "https://images.unsplash.com/photo-1598300188259-067ef3a66d4a"
              ],
              tags: ["读书空间", "宿舍改造", "生活方式"]
            },
            meta: {
              time: "1周前"
            },
            stats: {
              likes: 389,
              comments: 103,
              views: 1567,
              liked: false
            }
          }];
          break;
        default:
          this.posts = concernPosts;
      }
    },

    getTagColor(index) {
      return this.tagColors[index % this.tagColors.length];
    },

    toggleLike(post) {
      post.stats.liked = !post.stats.liked;
      post.stats.likes += post.stats.liked ? 1 : -1;
    },

    handleAvatarClick(userId) {
      if (this.$route.name === "user" && this.$route.query.userId === userId) {
        return;
      }
      this.$router.push({
        name: "user",
        query: { userId: userId }
      });
    },

    handleNameClick(userId) {
      userId = Number(userId);
      console.log("点击用户:", userId);
      if (this.$route.name === "user" && this.$route.query.userId === userId) {
        return;
      }
      this.$router.push({
        name: "user",
        query: { userId: userId }
      });
    },

    handleFollowClick(userId) {
      userId = Number(userId);
      console.log("关注用户:", userId);
      if (this.followingUsers.has(userId)) {
        this.followingUsers.delete(userId);
      } else {
        this.followingUsers.add(userId);
      }
      // 强制更新组件以反映关注状态变化
      this.$forceUpdate();
    },

    handlePostDetailClick(postId) {
      if (this.$route.name === "postDetail" && this.$route.query.postId === postId) {
        return;
      }
      this.$router.push({
        name: "postDetail",
        query: { postId: postId, userId: this.currentUserId }
      });
    },

    isShowConcernButton(userId) {
      userId = Number(userId);
      return this.currentUserId !== userId;
    },

    isFollowing(userId) {
      userId = Number(userId);
      return this.followingUsers.has(userId);
    },

    handleCommunityClick(communityId) {
      this.$router.push({
        name: "communityHome",
        query: { id: communityId }
      });
    },

    formatNumber(num) {
      if (num >= 10000) {
        return (num / 10000).toFixed(1) + "w";
      } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + "k";
      }
      return num.toString();
    }
  }
};
</script>

<style scoped>
/* 文本截断样式 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 卡片悬停效果 */
article:hover {
  transform: translateY(-4px);
}

/* 图片悬停效果 */
img {
  transition: transform 0.3s ease;
}

/* 按钮悬停效果 */
button {
  transition: all 0.2s ease;
}

/* 渐变动画 */
@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}


/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 4px;
}

::-webkit-scrollbar-track {
  background: #f8f9fa;
  border-radius: 2px;
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(to bottom, #62dbb7, #40aad4);
  border-radius: 2px;
}

::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(to bottom, #4ade80, #0ea5e9);
}

/* 微动效果 */
.group:hover .group-hover\:scale-105 {
  transform: scale(1.05);
}

/* 头像在线状态指示器动画 */
@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

</style>